import { defineStore } from 'pinia'
import type { UIState } from '@/types'

export const useUIStore = defineStore('ui', () => {
  // 状态
  const state = ref<UIState>({
    theme: 'light',
    sidebarCollapsed: false,
    activePanel: 'chat',
    showTaskPanel: true,
    showMCPPanel: false,
    windowSize: {
      width: window.innerWidth,
      height: window.innerHeight
    },
    panelSizes: {
      chat: 60,
      task: 40
    },
    isFullscreen: false,
    loading: {
      global: false,
      chat: false,
      tasks: false,
      mcp: false
    }
  })

  // 消息状态
  const errorMessage = ref<string>('')
  const successMessage = ref<string>('')

  // 计算属性
  const isDarkTheme = computed(() => state.value.theme === 'dark')
  const isLoading = computed(() => Object.values(state.value.loading).some(Boolean))
  const isMobile = computed(() => state.value.windowSize.width < 768)
  const isTablet = computed(() => 
    state.value.windowSize.width >= 768 && state.value.windowSize.width < 1200
  )
  const isDesktop = computed(() => state.value.windowSize.width >= 1200)

  // Actions
  const setTheme = (theme: 'light' | 'dark') => {
    state.value.theme = theme
    document.documentElement.setAttribute('data-theme', theme)
    localStorage.setItem('app-theme', theme)
  }

  const toggleTheme = () => {
    setTheme(state.value.theme === 'light' ? 'dark' : 'light')
  }

  const setActivePanel = (panel: 'chat' | 'tasks' | 'mcp' | 'settings') => {
    state.value.activePanel = panel
  }

  const toggleSidebar = () => {
    state.value.sidebarCollapsed = !state.value.sidebarCollapsed
  }

  const setSidebarCollapsed = (collapsed: boolean) => {
    state.value.sidebarCollapsed = collapsed
  }

  const toggleTaskPanel = () => {
    state.value.showTaskPanel = !state.value.showTaskPanel
    // 自动调整面板大小
    if (state.value.showTaskPanel) {
      state.value.panelSizes = { chat: 60, task: 40 }
    } else {
      state.value.panelSizes = { chat: 100, task: 0 }
    }
  }

  const setTaskPanelVisible = (visible: boolean) => {
    state.value.showTaskPanel = visible
    if (visible) {
      state.value.panelSizes = { chat: 60, task: 40 }
    } else {
      state.value.panelSizes = { chat: 100, task: 0 }
    }
  }

  const toggleMCPPanel = () => {
    state.value.showMCPPanel = !state.value.showMCPPanel
  }

  const setMCPPanelVisible = (visible: boolean) => {
    state.value.showMCPPanel = visible
  }

  const updateWindowSize = (size: { width: number; height: number }) => {
    state.value.windowSize = size
    
    // 响应式调整
    if (size.width < 1200 && state.value.showTaskPanel) {
      // 小屏幕时隐藏任务面板
      setTaskPanelVisible(false)
    } else if (size.width >= 1200 && !state.value.showTaskPanel) {
      // 大屏幕时显示任务面板
      setTaskPanelVisible(true)
    }
  }

  const adjustPanelSizes = (chatPercentage: number) => {
    const taskPercentage = 100 - chatPercentage
    state.value.panelSizes = {
      chat: Math.max(30, Math.min(80, chatPercentage)), // 限制在30%-80%之间
      task: Math.max(20, Math.min(70, taskPercentage))  // 限制在20%-70%之间
    }
  }

  const setFullscreen = (fullscreen: boolean) => {
    state.value.isFullscreen = fullscreen
  }

  const toggleFullscreen = async () => {
    try {
      if (!document.fullscreenElement) {
        await document.documentElement.requestFullscreen()
        setFullscreen(true)
      } else {
        await document.exitFullscreen()
        setFullscreen(false)
      }
    } catch (error) {
      console.error('Failed to toggle fullscreen:', error)
    }
  }

  // 加载状态管理
  const setLoading = (key: keyof UIState['loading'], loading: boolean) => {
    state.value.loading[key] = loading
  }

  const setGlobalLoading = (loading: boolean) => {
    setLoading('global', loading)
  }

  const setChatLoading = (loading: boolean) => {
    setLoading('chat', loading)
  }

  const setTasksLoading = (loading: boolean) => {
    setLoading('tasks', loading)
  }

  const setMCPLoading = (loading: boolean) => {
    setLoading('mcp', loading)
  }

  // 消息管理
  const showError = (message: string) => {
    errorMessage.value = message
    // 自动清除错误消息
    setTimeout(() => {
      clearError()
    }, 5000)
  }

  const showSuccess = (message: string) => {
    successMessage.value = message
    // 自动清除成功消息
    setTimeout(() => {
      clearSuccess()
    }, 3000)
  }

  const clearError = () => {
    errorMessage.value = ''
  }

  const clearSuccess = () => {
    successMessage.value = ''
  }

  const clearAllMessages = () => {
    clearError()
    clearSuccess()
  }

  // UI辅助方法
  const focusSearchInput = () => {
    // 聚焦搜索输入框
    const searchInput = document.querySelector('input[type="search"]') as HTMLInputElement
    if (searchInput) {
      searchInput.focus()
    }
  }

  const showHelpDialog = () => {
    // 显示帮助对话框
    // 这里可以集成一个帮助模态框
    console.log('Show help dialog')
  }

  // 重置状态
  const resetUI = () => {
    state.value = {
      theme: 'light',
      sidebarCollapsed: false,
      activePanel: 'chat',
      showTaskPanel: true,
      showMCPPanel: false,
      windowSize: {
        width: window.innerWidth,
        height: window.innerHeight
      },
      panelSizes: {
        chat: 60,
        task: 40
      },
      isFullscreen: false,
      loading: {
        global: false,
        chat: false,
        tasks: false,
        mcp: false
      }
    }
    clearAllMessages()
  }

  // 保存UI状态到本地存储
  const saveUIState = () => {
    const stateToSave = {
      theme: state.value.theme,
      sidebarCollapsed: state.value.sidebarCollapsed,
      activePanel: state.value.activePanel,
      showTaskPanel: state.value.showTaskPanel,
      showMCPPanel: state.value.showMCPPanel,
      panelSizes: state.value.panelSizes
    }
    localStorage.setItem('ui-state', JSON.stringify(stateToSave))
  }

  // 从本地存储恢复UI状态
  const restoreUIState = () => {
    try {
      const savedState = localStorage.getItem('ui-state')
      if (savedState) {
        const parsed = JSON.parse(savedState)
        Object.assign(state.value, parsed)
        // 应用主题
        document.documentElement.setAttribute('data-theme', state.value.theme)
      }
    } catch (error) {
      console.error('Failed to restore UI state:', error)
    }
  }

  // 监听状态变化并保存
  watch(
    () => state.value,
    () => {
      saveUIState()
    },
    { deep: true }
  )

  return {
    // 状态
    state: readonly(state),
    errorMessage: readonly(errorMessage),
    successMessage: readonly(successMessage),

    // 计算属性
    isDarkTheme,
    isLoading,
    isMobile,
    isTablet,
    isDesktop,

    // Actions
    setTheme,
    toggleTheme,
    setActivePanel,
    toggleSidebar,
    setSidebarCollapsed,
    toggleTaskPanel,
    setTaskPanelVisible,
    toggleMCPPanel,
    setMCPPanelVisible,
    updateWindowSize,
    adjustPanelSizes,
    setFullscreen,
    toggleFullscreen,

    // 加载状态
    setLoading,
    setGlobalLoading,
    setChatLoading,
    setTasksLoading,
    setMCPLoading,

    // 消息管理
    showError,
    showSuccess,
    clearError,
    clearSuccess,
    clearAllMessages,

    // UI辅助
    focusSearchInput,
    showHelpDialog,

    // 状态管理
    resetUI,
    saveUIState,
    restoreUIState
  }
})